﻿using System;
using System.Globalization;

namespace Matrix.Common.Utility
{
    public static class StringLib
    {
        /// <summary>
        /// 检查是否存在某Cookie
        /// </summary>
        /// <param name="mainName"></param>
        /// <returns></returns>
        public static bool CheckCookieIsExist(string mainName)
        {
            bool result = false;
            var cookie = System.Web.HttpContext.Current.Request.Cookies[mainName];
            if (cookie != null)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 获取Cookie值
        /// </summary>
        /// <param name="mainName">Cookie主名称</param>
        /// <param name="keyName">Cookie Key名称</param>
        /// <returns></returns>
        public static string GetCookieValue(string mainName, string keyName)
        {
            string strResult = string.Empty;
            var cookie = System.Web.HttpContext.Current.Request.Cookies[mainName];
            if (cookie != null)
            {
                strResult = cookie.Values[keyName];
            }
            return strResult;
        }

        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string strResult;
            strResult = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null
                           ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(CultureInfo.InvariantCulture) :
                              System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(CultureInfo.InvariantCulture);
            if (strResult.Length == 3)
            {
                #pragma warning disable 618
                System.Net.IPHostEntry ipHost = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
                #pragma warning restore 618
                System.Net.IPAddress[] addr = ipHost.AddressList;
                strResult = addr[0].ToString().Trim();
            }
            return strResult;
        }

        /// <summary>
        /// 字符切取
        /// </summary>
        /// <param name="str">原本字符</param>
        /// <param name="maxLength">截取到X位</param>
        /// <returns></returns>
        public static string TruncateTo(this string str, int maxLength)
        {
            return str.Substring(0, Math.Min(str.Length, maxLength));
        }
    }
}
